/*
 * @Date         : 2024-05-12 17:44:11 星期0
 * @Author       : xut
 * @Description  :
 */
import grpc from "@grpc/grpc-js"

let unaryRequestCount = 0
let streamingRequestCount = 0

export const echoServiceImpl = {
  unaryEcho: (call, cb) => {
    unaryRequestCount++

    // 客户端配置的 maxAttempts = 4， 1次正常发送+3次失败重试
    if (unaryRequestCount % 4 === 0) {
      console.log("[Unary] request succeed count: ", unaryRequestCount)
      const response = { value: "Hello " + call.request.name }
      cb(null, response)
    } else {
      console.log("[Unary] request failed count: ", unaryRequestCount)
      call.emit("error", {
        // 客户端配置触发重试的状态 retryableStatusCodes: ['UNAVAILABLE']
        code: grpc.status.UNAVAILABLE,
        details: `test retry, count: ${unaryRequestCount}`,
      })
    }
  },

  serverStreamingEcho: (call) => {
    streamingRequestCount++

    // 客户端配置的 maxAttempts = 4， 1次正常发送+3次失败重试
    if (streamingRequestCount % 4 === 0) {
      console.log("[Streaming] request succeed count: ", streamingRequestCount)

      const hello = "Hello From Server"

      for (let i = 0; i < hello.length; i++) {
        call.write({ value: hello[i] })
      }

      call.end()
    } else {
      console.log("[Streaming] request failed count: ", streamingRequestCount)
      call.emit("error", {
        // 客户端配置触发重试的状态 retryableStatusCodes: ['UNAVAILABLE']
        code: grpc.status.UNAVAILABLE,
        details: `test retry, count: ${streamingRequestCount}`,
      })
    }
  },
}
